const int sensorPin = PA0;    // pin that the sensor is attached to

// Variables:
int sensorMin = 0;   // minimum sensor value
int sensorMax = 4000;      // maximum sensor value
int sensorValue = 0;    // the sensor value


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(PC13, PWM);
  pinMode(sensorPin, INPUT_ANALOG);

  // 5秒来获取 ADC的范围 -- 精细化 --- 此过程硬件要 将最大和最小值 触控到
  Serial.print("Start Calibration");
  while (millis() < 5000) {
    sensorValue = analogRead(sensorPin);

    // Record the maximum sensor value:
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }

    // Record the minimum sensor value:
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }
  Serial.print("End Calibration");

}

void loop() {
  // Read the sensor:
  sensorValue = analogRead(sensorPin);

  // Apply the calibration to the sensor reading:
  sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 65535);

  // In case the sensor value is outside the range seen during calibration:
  sensorValue = constrain(sensorValue, 0, 65535);
  Serial.println(sensorValue);
  // Fade the LED using the calibrated value:
  pwmWrite(PC13, sensorValue);
}
